#include "Common.h"

initSing(CalendarManager);

//	CalendarManager - Part. For the Session - Part see below!

CalendarManager::CalendarManager()
{
}

void CalendarManager::AddCalendarEvent(CalendarEntry* event)
{
	m_calendarevents.push_back(event);
	RealmPacket data(SMSG_CALENDAR_SEND_EVENT);
	data << ui8(1) << event->GetCreator()->GetNewGUID() << ui32(0xDDE2C); // last one is blargh....
	data << ui32(0) << event->title << event->description;
	data << event->type << ui8(0) << ui8(0x64) << ui8(0) << ui16(0);
	data << event->dungeonid << event->flags << event->ftime;
	data << ui32(0) << ui32(event->m_invited.size());

	for(set<Player*>::iterator itr = event->m_invited.begin(); itr != event->m_invited.end(); ++itr)
		data << (*itr)->GetNewGUID();

	data << ui32(0x020305) << ui32(0x7C758B) << ui32(0) << ui32(0); // no idea about that...

	for(set<Player*>::iterator itr = event->m_invited.begin(); itr != event->m_invited.end(); ++itr)
		(*itr)->GetSession()->SendPacket(&data);
	Log->Notice("Calendar", "Adding event '%s' on %02u:%02u (%02u.%02u.%04u) with %u members.", event->title, event->GetHoure(),
		event->GetMinute(), event->GetDay(), event->GetMonth(), event->GetYear(), event->m_invited.size());
}

CalendarEntry::CalendarEntry() : Day(*this), Houre(*this), Minute(*this), Year(*this), Month(*this)
{
	Day[&CalendarEntry::GetDay];
	Houre[&CalendarEntry::GetHoure];
	Minute[&CalendarEntry::GetMinute];
	Year[&CalendarEntry::GetYear];
	Month[&CalendarEntry::GetMonth];
}

ui32 CalendarEntry::GetDay()
{
	return ((ftime & 0x7C000) >> 14) + 1;
}

ui32 CalendarEntry::GetHoure()
{
	return (ftime & 0x7C0) >> 6;
}

ui32 CalendarEntry::GetMinute()
{
	return (ftime & 0x3F);
}

ui32 CalendarEntry::GetMonth()
{
	return ((ftime & 0xF00000) >> 20) + 1;
}

ui32 CalendarEntry::GetYear()
{
	return ((ftime & 0xFF000000) >> 24) + 2000;
}

void Session::HandleCalendarAddEvent(RealmPacket& data)
{
	char title[255], description[1024];
	ui8 type;
	ui32 time, id;
	data >> title >> description >> type;
	data.RemoveData(5); // just dont know what to do with them, its always the same :(
	data >> id >> time;
	CalendarEntry* ce = new CalendarEntry;
	strcpy_s<255>(ce->title, title);
	strcpy_s<1024>(ce->description, description);
	ce->dungeonid = id;
	ce->ftime = time;
	ce->type = type;
	ui32 num_players;
	data >> ce->unk32 >> ce->flags >> num_players;
	for(ui32 i = 0; i < num_players; ++i)
	{
		WoWGuid tmpguid;
		data >> tmpguid;
		Player* inv = miscmgr->GetPlayer(tmpguid.GetOldGuid());
		if(inv)
			ce->m_invited.insert(inv);
	}
	sCalendarManager.AddCalendarEvent(ce);
}